package com.yanyilu.qiubite.service;

import com.google.zxing.WriterException;
import com.yanyilu.qiubite.entity.Storyline;
import com.yanyilu.qiubite.jpa.StorylineJpa;
import com.yanyilu.qiubite.util.Base64Util;
import com.yanyilu.qiubite.util.QRCodeGeneratorUtil;
import com.yanyilu.qiubite.util.R;
import com.yanyilu.qiubite.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Optional;

@Service
public class StorylineService {
    @Autowired
    StorylineJpa storylineJpa;

    @Autowired
    UploadService uploadService;

    public void addStoryline(Storyline storyline) {
        storylineJpa.save(storyline);
    }

    public void deleteStoryline(Integer lineId) {
        storylineJpa.deleteById(lineId);
    }

    public void deleteBySpotId(Integer lineId, Integer spotId) {
        storylineJpa.deleteByLinedAndSpotId(lineId,spotId);
    }

    public Page<Storyline> getListByPartId(Integer partId, Pageable pageable) {
        return storylineJpa.findByPartId(partId,pageable);
    }

    public Page<Storyline> getListByPartIdAndSportId(Integer partId, Pageable pageable) {
        return storylineJpa.findByPartIdAndSpotId(partId,pageable);
    }

    /**
     * 创建故事线二维码
     * @param lineId
     * @return
     */
    public R createCode(Integer lineId) {
        String lineAnswer = storylineJpa.findLineAnswerById(lineId);
        //加密
        String encode = Base64Util.encode(lineAnswer);
        String fileName = "qrcode"+System.currentTimeMillis()+".png";
        try {
            String path = QRCodeGeneratorUtil.generateQRCodeImage(encode, 350, 350, fileName);
            String url = uploadService.toOSS(fileName, path);
            return R.ok().put("url", url);
        } catch (WriterException e) {
            e.printStackTrace();
            return R.error();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }

    }

    //根据id查询
    public R findById(Integer lineId) {
        Optional<Storyline> optional = storylineJpa.findById(lineId);
        if(optional.isPresent()){
            Storyline storyline = optional.get();
            return R.ok().put("storyline",storyline);
        }else{
            return R.error(ResultCode.DATA_IS_WRONG);
        }
    }
}
